// 获取当前日期和时间的格式化字符串
export function getFormattedCurrentDateTime(): string {
    const now = new Date();
    const year = now.getFullYear();
    const month = padZero(now.getMonth() + 1);
    const day = padZero(now.getDate());
    const hours = padZero(now.getHours());
    const minutes = padZero(now.getMinutes());
    const seconds = padZero(now.getSeconds());
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function padZero(num: number): string {
    return num < 10 ? `0${num}` : num.toString();
}

// 验证邮箱格式
export function validateEmail(email: string): boolean {
    const reg =
        /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@(([^<>()[\]\\.,;:\s@"]+\.)+[^<>()[\]\\.,;:\s@"]{2,})$/i;
    return reg.test(email);
}

// 验证手机号格式
export function validatePhone(phone: string): boolean {
    const reg = /^(?:(?:\+|00)86)?1\d{10}$/;
    return reg.test(phone);
}

//uuid函数
export function generateUUID(): string {
    // 检查是否支持crypto.randomUUID  
    if (typeof crypto !== 'undefined' && crypto.randomUUID) {
        return crypto.randomUUID();
    }

    // 回退到手动实现 
    const byteToHex: string[] = [];
    for (let i = 0; i < 256; ++i) {
        byteToHex.push((i + 0x100).toString(16).substr(1));
    }

    const buffer = new Uint8Array(16);
    crypto.getRandomValues(buffer);

    // 设置版本和变体 
    buffer[6] = (buffer[6] & 0x0f) | 0x40; // Version 4 
    buffer[8] = (buffer[8] & 0x3f) | 0x80; // Variant is 10 

    function bytesToUuid(bytes: Uint8Array): string {
        let uuid = '';
        for (let i = 0; i < 16; ++i) {
            if (i === 4 || i === 6 || i === 8 || i === 10) uuid += '-';
            uuid += byteToHex[bytes[i]];
        }
        return uuid;
    }

    return bytesToUuid(buffer);
}
